<template>
  <el-row :gutter="20" class="app-container">
    <Splitpanes>
      <pane size="16" v-if="$auth.hasRoleOr(['admin','manager','fishingceo'])">
        <el-col>
          <div class="head-container">
            <el-tree
              :data="deptOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
      </pane>
      <pane :size="$auth.hasRoleOr(['admin','manager','fishingceo']) ? 84 : 100">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['pond:appointment:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['pond:appointment:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['pond:appointment:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['pond:appointment:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="appointmentList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="预约ID" align="center" prop="id" />
          <el-table-column label="所属钓场" align="center" prop="deptName" />
          <el-table-column label="所属鱼塘" align="center" prop="pondName" />
          <el-table-column label="预约状态" align="center" prop="status">
            <template #default="scope">
              <el-tag :type="getAppointmentStatusTagType(scope.row.status)">
                {{ getAppointmentStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="200"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['pond:appointment:edit']"
                >修改</el-button
              >
              <el-button
                link
                type="success"
                icon="Check"
                @click="handleCheckin(scope.row)"
                v-hasPermi="['pond:appointment:checkin']"
                >签到管理</el-button
              >
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['pond:appointment:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改预约信息对话框 -->
        <el-dialog :title="title" v-model="open" width="80%" append-to-body>
          <el-form
            ref="appointmentRef"
            :model="form"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="所属钓场" prop="deptId">
              <DeptSelect
                v-model="form.deptId"
                @change="handleDeptChange"
              />
            </el-form-item>
            <el-form-item label="所属鱼塘" prop="pondId">
              <PondSelect
                v-model="form.pondId"
                :dept-id="form.deptId"
                @change="handlePondChange"
              />
            </el-form-item>
            <el-form-item label="预约状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择预约状态">
                <el-option 
                  v-for="option in appointmentStatusOptions"
                  :key="option.value"
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
            <el-form-item label="预约用户" prop="userId">
              <el-select 
                v-model="form.userId" 
                placeholder="请选择预约用户"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="user in userOptions"
                  :key="user.userId"
                  :label="user.nickName + '(' + user.userName + ')'"
                  :value="user.userId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="预约时间段" prop="timeSegments">
              <div
                v-for="(segment, index) in form.timeSegments"
                :key="index"
                class="time-segment"
              >
                <el-row gutter="10">
                  <el-col :span="5">
                    <el-form-item
                      label="钓位"
                      :prop="'timeSegments.' + index + '.seatId'"
                      label-width="60px"
                    >
                      <el-select
                        v-model="segment.seatId"
                        placeholder="选择钓位"
                        style="width: 100%"
                      >
                        <el-option
                          v-for="item in seatOptions"
                          :key="item.id"
                          :label="item.code"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="5">
                    <el-form-item
                      label="日期"
                      :prop="'timeSegments.' + index + '.appointmentDate'"
                      label-width="60px"
                    >
                      <el-date-picker
                        v-model="segment.appointmentDate"
                        type="date"
                        placeholder="选择日期"
                        value-format="YYYY-MM-DD"
                        style="width: 100%"
                        :disabled-date="disabledDate"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="5">
                    <el-form-item
                      label="开始"
                      :prop="'timeSegments.' + index + '.startTime'"
                      label-width="50px"
                    >
                      <el-time-select
                        v-model="segment.startTime"
                        placeholder="开始时间"
                        style="width:  150px"
                        :start="getStartTimeLimit(segment.appointmentDate)"
                        end="23:30"
                        step="00:30"
                        @change="(value) => handleStartTimeChange(index, value)"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="5">
                    <el-form-item
                      label="结束"
                      :prop="'timeSegments.' + index + '.endTime'"
                      label-width="50px"
                    >
                      <el-time-select
                        v-model="segment.endTime"
                        placeholder="结束时间"
                        style="width:  150px"
                        start="00:00"
                        end="23:30"
                        step="00:30"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-button
                      type="danger"
                      icon="Delete"
                      size="small"
                      @click="removeTimeSegment(index)"
                      v-if="form.timeSegments.length > 1"
                      style="margin-top: 32px;"
                    ></el-button>
                  </el-col>
                </el-row>
              </div>
              <el-button type="primary" icon="Plus" @click="addTimeSegment"
                >添加时间段</el-button
              >
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 签到管理对话框 -->
        <el-dialog title="签到管理" v-model="checkinOpen" width="800px" append-to-body>
          <div class="checkin-header">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="预约ID">{{ checkinData.id }}</el-descriptions-item>
              <el-descriptions-item label="预约用户">{{ checkinData.nickName }}</el-descriptions-item>
              <el-descriptions-item label="所属钓场">{{ checkinData.deptName }}</el-descriptions-item>
              <el-descriptions-item label="所属鱼塘">{{ checkinData.pondName }}</el-descriptions-item>
            </el-descriptions>
          </div>
          
          <div class="checkin-content">
            <h4>预约时间段列表</h4>
            <el-table :data="checkinData.timeSegments" border style="width: 100%">
              <el-table-column label="钓位" align="center" prop="seatCode" width="80" />
              <el-table-column label="预约日期" align="center" prop="appointmentDate" />
              <el-table-column label="开始时间" align="center" width="100">
                <template #default="scope">
                  {{ scope.row.startTime ? scope.row.startTime.substring(0, 5) : '' }}
                </template>
              </el-table-column>
              <el-table-column label="结束时间" align="center" width="100">
                <template #default="scope">
                  {{ scope.row.endTime ? scope.row.endTime.substring(0, 5) : '' }}
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center" width="100">
                <template #default="scope">
                  <el-tag :type="getTimeSegmentStatusType(scope.row.status)">
                    {{ getTimeSegmentStatusLabel(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="120">
                <template #default="scope">
                  <el-button
                    v-if="scope.row.status !== 5"
                    type="primary"
                    size="small"
                    @click="handleConfirmCheckin(scope.row)"
                    :loading="scope.row.loading"
                    v-hasPermi="['pond:appointment:checkin']"
                  >
                    确认签到
                  </el-button>
                  <span v-else style="color: #909399; font-size: 12px;">
                    钓鱼中
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="checkinOpen = false">关 闭</el-button>
            </div>
          </template>
        </el-dialog>
      </pane>
    </Splitpanes>
  </el-row>
</template>

<script setup name="Appointment">
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { listUser } from "@/api/system/user";
import { useDeptTree } from "@/utils/deptTreeUtils";
import { listPond } from "@/api/pond/pond";
import { listSeat } from "@/api/pond/seat";
import PondSelect from "@/components/PondSelect/index.vue";
import DeptSelect from "@/components/DeptSelect/index.vue";
import {
  listAppointment,
  getAppointment,
  delAppointment,
  addAppointment,
  updateAppointment,
  getUserAppointment
} from "@/api/pond/appointment";
import { createFromAppointment } from "@/api/pond/order";
import useUserStore from '@/store/modules/user';
import { getAppointmentStatusOptions, getAppointmentStatusLabel } from "@/utils/enums";

const { proxy } = getCurrentInstance();

// 获取当前日期 YYYY-MM-DD 格式
function getCurrentDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 根据开始时间计算结束时间（+4小时）
function getEndTimeFromStartTime(startTime) {
  if (!startTime) return '';
  
  const [hours, minutes] = startTime.split(':').map(Number);
  const startDate = new Date();
  startDate.setHours(hours, minutes, 0, 0);
  
  // 加4小时
  const endDate = new Date(startDate.getTime() + 4 * 60 * 60 * 1000);
  
  const endHours = String(endDate.getHours()).padStart(2, '0');
  const endMinutes = String(endDate.getMinutes()).padStart(2, '0');
  
  return `${endHours}:${endMinutes}`;
}

// 创建默认时间段
function createDefaultTimeSegment() {
  const now = new Date();
  const currentHour = now.getHours();
  const currentMinute = now.getMinutes();
  
  let targetHour = currentHour;
  let targetMinute = 0;
  
  // 判断当前时间应该预约哪个时段
  if (currentMinute >= 15 && currentMinute < 45) {
    // 15-44分钟：预约下一个整点（如16:15-16:44预约17:00）
    targetHour += 1;
    targetMinute = 0;
  } else if (currentMinute >= 45) {
    // 45-59分钟：预约下下个半小时（如16:45-16:59预约17:30）
    targetHour += 1;
    targetMinute = 30;
  } else {
    // 0-14分钟：预约当前半小时（如16:00-16:14预约16:30）
    targetMinute = 30;
  }
  
  // 再加上提前30分钟的要求
  const targetTime = new Date();
  targetTime.setHours(targetHour, targetMinute, 0, 0);
  const minAllowedTime = new Date(now.getTime() + 30 * 60 * 1000);
  
  // 如果计算出的时间还不满足提前30分钟，则继续往后推
  if (targetTime < minAllowedTime) {
    if (targetMinute === 0) {
      targetMinute = 30;
    } else {
      targetHour += 1;
      targetMinute = 0;
    }
  }
  
  const startTime = `${String(targetHour).padStart(2, '0')}:${String(targetMinute).padStart(2, '0')}`;
  const endTime = getEndTimeFromStartTime(startTime);
  
  return {
    seatId: undefined,
    appointmentDate: getCurrentDate(),
    startTime: startTime,
    endTime: endTime,
  };
}

const appointmentList = ref([]);
const open = ref(false);
const checkinOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const checkinData = ref({});

// 使用部门树工具
const {
  deptOptions,
  enabledDeptOptions,
  getDeptTree,
  handleFormDeptNodeClick,
  handleSidebarDeptNodeClick,
} = useDeptTree();
const pondOptionList = ref([]);
const formPondOptionList = ref([]);
const seatOptions = ref([]);
const userOptions = ref([]);

// 预约状态选项
const appointmentStatusOptions = ref(getAppointmentStatusOptions());

const data = reactive({
  form: {
    userId: undefined,
    deptId: undefined,
    pondId: undefined,
    status: 0,
    timeSegments: [createDefaultTimeSegment()],
    remark: undefined,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: undefined,
    pondId: undefined,
    status: undefined,
  },
  rules: {
    deptId: [{ required: true, message: "所属钓场不能为空", trigger: "blur" }],
    pondId: [{ required: true, message: "所属鱼塘不能为空", trigger: "blur" }],
    status: [
      { required: true, message: "预约状态不能为空", trigger: "change" },
    ],
    userId: [
      { required: true, message: "预约用户不能为空", trigger: "change" },
    ],
    timeSegments: [
      { required: true, message: "预约时间段不能为空", trigger: "change" },
      { validator: validateTimeSegments, trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 侧边栏部门树节点单击事件 */
function handleNodeClick(data) {
  handleSidebarDeptNodeClick(data, (deptId) => {
    queryParams.value.deptId = deptId;
    handleQuery();
  });
}

/** 获取鱼塘选项 */
function getOptions() {
  const params = {
    pageNum: 1,
    pageSize: 10,
    deptId: queryParams.value.deptId,
  };
  listPond(params).then((response) => {
    pondOptionList.value = response.rows || [];
  });
}

/** 获取钓位选项 */
function getSeatOptions(pondId) {
  const params = {
    pageNum: 1,
    pageSize: 100,
    pondId: pondId,
  };
  listSeat(params).then((response) => {
    seatOptions.value = response.rows || [];
  });
}

/** 获取钓友用户列表 */
function getFishingUsers() {
  const params = {
    pageNum: 1,
    pageSize: 1000,
    roleId: 2, // 钓友角色ID
  };
  listUser(params).then((response) => {
    userOptions.value = response.rows || [];
  });
}

/** 查询预约列表 */
function getList() {
  loading.value = true;
  listAppointment(queryParams.value).then((response) => {
    appointmentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    userId: undefined,
    deptId: undefined,
    pondId: undefined,
    status: 0,
    timeSegments: [createDefaultTimeSegment()],
    remark: undefined,
  };
  proxy.resetForm("appointmentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  proxy.$refs.deptTreeRef && proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.deptId = queryParams.value.deptId;
  if (form.value.deptId) {
    const params = {
      pageNum: 1,
      pageSize: 10,
      deptId: form.value.deptId,
    };
    listPond(params).then((response) => {
      formPondOptionList.value = response.rows || [];
    });
  }
  open.value = true;
  title.value = "添加预约信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getAppointment(_id).then(async (response) => {
    form.value = response.data;
    
    // 创建异步任务数组
    const loadTasks = [];
    
    // 如果有部门ID，加载对应的鱼塘选项
    if (form.value.deptId) {
      const pondTask = listPond({
        pageNum: 1,
        pageSize: 10,
        deptId: form.value.deptId,
      }).then((pondResponse) => {
        formPondOptionList.value = pondResponse.rows || [];
      });
      loadTasks.push(pondTask);
    }
    
    // 如果有鱼塘ID，加载对应的钓位选项
    if (form.value.pondId) {
      const seatTask = listSeat({
        pageNum: 1,
        pageSize: 100,
        pondId: form.value.pondId,
      }).then((seatResponse) => {
        seatOptions.value = seatResponse.rows || [];
      });
      loadTasks.push(seatTask);
    }
    
    // 等待所有数据加载完成后再打开对话框
    await Promise.all(loadTasks);
    
    // 使用 nextTick 确保 DOM 更新完成
    await proxy.$nextTick();
    
    open.value = true;
    title.value = "修改预约信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["appointmentRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateAppointment(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAppointment(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除预约信息编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delAppointment(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "appointment/export",
    {
      ...queryParams.value,
    },
    `appointment_${new Date().getTime()}.xlsx`
  );
}

/** 表单中的部门树节点点击事件 */
function handleDeptNodeClick(data, node, e) {
  handleFormDeptNodeClick(data, node, e, (deptId) => {
    form.value.deptId = deptId;
    handleDeptChange(deptId);
  }, proxy, 'deptTreeSelectRef');
}

/** 所属钓场选择变化事件 */
function handleDeptChange(deptId) {
  if (deptId) {
    const params = {
      pageNum: 1,
      pageSize: 10,
      deptId: deptId,
    };
    listPond(params).then((response) => {
      formPondOptionList.value = response.rows || [];
      form.value.pondId = null;
    });
  } else {
    formPondOptionList.value = [];
    form.value.pondId = null;
  }
}

/** 鱼塘选择变化事件 */
function handlePondChange(pondId) {
  if (pondId) {
    getSeatOptions(pondId);
  } else {
    seatOptions.value = [];
  }
}

/** 添加时间段 */
function addTimeSegment() {
  form.value.timeSegments.push(createDefaultTimeSegment());
}

/** 删除时间段 */
function removeTimeSegment(index) {
  form.value.timeSegments.splice(index, 1);
}


/** 处理开始时间变化 */
function handleStartTimeChange(index, value) {
  if (value) {
    // 当开始时间改变时，自动计算结束时间
    const endTime = getEndTimeFromStartTime(value);
    form.value.timeSegments[index].endTime = endTime;
  }
}

/** 获取状态标签类型 */
function getStatusTagType(status) {
  const typeMap = {
    0: 'warning',  // 待确认
    1: 'success',  // 已确认
    2: 'danger',   // 已取消
    3: 'info'      // 已完成
  };
  return typeMap[status] || '';
}

/** 禁用日期 - 不能选择今天之前的日期 */
function disabledDate(time) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
}

/** 获取开始时间限制 */
function getStartTimeLimit(appointmentDate) {
  const today = getCurrentDate();
  
  if (appointmentDate === today) {
    const now = new Date();
    const currentHour = now.getHours();
    const currentMinute = now.getMinutes();
    
    // 计算最早可预约时间（当前时间+30分钟）
    const minTime = new Date(now.getTime() + 30 * 60 * 1000);
    let minHour = minTime.getHours();
    let minMinute = minTime.getMinutes();
    
    // 调整到下一个半小时整点
    if (minMinute > 30) {
      minHour += 1;
      minMinute = 0;
    } else if (minMinute > 0) {
      minMinute = 30;
    }
    
    return `${String(minHour).padStart(2, '0')}:${String(minMinute).padStart(2, '0')}`;
  }
  
  return "00:00";
}

/** 验证时间段 */
function validateTimeSegments(rule, value, callback) {
  if (!value || value.length === 0) {
    callback(new Error('预约时间段不能为空'));
    return;
  }
  
  for (let i = 0; i < value.length; i++) {
    const segment = value[i];
    
    // 检查必填字段
    if (!segment.appointmentDate || !segment.startTime || !segment.endTime) {
      callback(new Error(`第${i + 1}个时间段信息不完整`));
      return;
    }
    
    // 检查预约时间是否符合提前半小时的要求
    const appointmentDateTime = new Date(`${segment.appointmentDate} ${segment.startTime}`);
    const now = new Date();
    const minAllowedTime = new Date(now.getTime() + 30 * 60 * 1000); // 当前时间+30分钟
    
    if (appointmentDateTime < minAllowedTime) {
      callback(new Error(`第${i + 1}个时间段：预约时间必须提前至少30分钟`));
      return;
    }
    
    // 检查开始时间是否早于结束时间
    const startTime = new Date(`2000-01-01 ${segment.startTime}`);
    const endTime = new Date(`2000-01-01 ${segment.endTime}`);
    
    if (startTime >= endTime) {
      callback(new Error(`第${i + 1}个时间段：开始时间必须早于结束时间`));
      return;
    }
  }
  
  callback();
}

// 监听部门选择变化
watch(
  () => queryParams.value.deptId,
  (newVal) => {
    if (newVal) {
      getOptions();
    } else {
      pondOptionList.value = [];
    }
  }
);

/** 签到管理按钮操作 */
function handleCheckin(row) {
  const _id = row.id || ids.value;
  getAppointment(_id).then((response) => {
    checkinData.value = response.data;
    // 为每个时间段添加loading状态
    if (checkinData.value.timeSegments) {
      checkinData.value.timeSegments = checkinData.value.timeSegments.map(segment => ({
        ...segment,
        loading: false
      }));
    }
    checkinOpen.value = true;
  });
}

/** 获取预约状态文字 */
function getAppointmentStatusText(status) {
  const statusMap = {
    0: '待确认',
    1: '已预约',
    2: '已取消',
    3: '已完成',
    4: '已过期',
    5: '钓鱼中'
  };
  return statusMap[status] || '未知';
}

/** 获取预约状态标签类型 */
function getAppointmentStatusTagType(status) {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'danger',
    3: 'success',
    4: 'info',
    5: 'warning'
  };
  return typeMap[status] || 'info';
}

/** 获取时间段状态标签 */
function getTimeSegmentStatusLabel(status) {
  const statusMap = {
    1: '已预约',
    5: '钓鱼中'
  };
  return statusMap[status] || '未知';
}

/** 获取时间段状态标签类型 */
function getTimeSegmentStatusType(status) {
  const typeMap = {
    1: 'success',
    5: 'warning'
  };
  return typeMap[status] || 'info';
}

/** 确认签到操作 */
function handleConfirmCheckin(timeSegment) {
  proxy.$modal.confirm(`确认为用户"${checkinData.value.nickName}"在钓位"${timeSegment.seatCode}"签到吗？`).then(() => {
    // 设置loading状态
    timeSegment.loading = true;
    
    // 调用签到接口
    createFromAppointment(timeSegment.id).then(response => {
      proxy.$modal.msgSuccess("签到成功，已生成订单");
      timeSegment.loading = false;
      // 可以选择关闭弹窗或刷新数据
      checkinOpen.value = false;
      getList(); // 刷新预约列表
    }).catch(error => {
      console.error('签到失败:', error);
      timeSegment.loading = false;
      proxy.$modal.msgError("签到失败，请重试");
    });
  }).catch(() => {
    // 取消操作
  });
}

getDeptTree();
getOptions();
getFishingUsers();
getList();
</script>

<style scoped>
.time-segment {
  width: 100%;
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fafafa;
}

.time-segment .el-form-item {
  margin-bottom: 0;
}

.time-segment .el-row {
  align-items: flex-end;
}

/* 签到管理弹窗样式 */
.checkin-header {
  margin-bottom: 20px;
}

.checkin-content h4 {
  margin: 20px 0 15px 0;
  color: #303133;
  font-weight: 600;
}

.checkin-content .el-table {
  margin-top: 10px;
}
</style>
